/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

package dao.jpa;

import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.Query;

/**
 *
 * @author Thuan
 */
public abstract class JPADao<T> {
    
    protected JPAUtil jpaUtil;
    
    public JPADao(){
        jpaUtil = JPAUtil.getInstance();
    }
    
    public void incluir(T obj){
        
        EntityManager em = jpaUtil.createEM();
        
        try{
            em.getTransaction().begin();
            em.persist(obj);
            em.getTransaction().commit();
        }finally{
            em.close();
        }
    }
    
     public abstract Class<T> classEntidade();
    
    public List<T> listarTodos(){
        EntityManager em = jpaUtil.createEM();
        List<T> lista = null;
        
        try{
            Query consulta = em.createQuery("Select o from " + classEntidade().getName() + " o");
            lista = consulta.getResultList();
        }finally{
            em.close();
        }
        return lista;
    }
    
    public void alterar(T obj) {
        EntityManager em = jpaUtil.createEM();
        try{
            em.getTransaction().begin();
            em.merge(obj);
            em.getTransaction().commit();
        }finally{
            em.close();
        }
    }
    
    public void excluir(T obj) {
        EntityManager em = jpaUtil.createEM();
        try{
            em.getTransaction().begin();
            em.remove(em.merge(obj));
            em.getTransaction().commit();
        }finally{
            em.close();
        }
    }
    
    public T buscarPorId(int id) {
        T obj;
        EntityManager em = jpaUtil.createEM();
        try{
            obj = em.find(classEntidade(), id);
        }finally{
            em.close();
        }
        return obj;
    }
    
}
